package be.groept.ace.enquete.servlets;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import be.groept.ace.enquete.model.beans.Survey;
import be.groept.ace.enquete.model.beans.User;
import be.groept.ace.enquete.model.dao.DAOCommand;
import be.groept.ace.enquete.model.dao.DAOFactory;
import be.groept.ace.enquete.model.dao.DAOManager;
import be.groept.ace.enquete.model.exceptions.DAOException;
import be.groept.ace.enquete.utils.BeanUtils;

/**
 * Servlet implementation class AdminEnqueteServlet
 */
@WebServlet("/admin/enquete/*")
public class AdminEnqueteServlet extends AdminServlet {
	
	private static final long serialVersionUID = 1L;
	private static Logger logger = Logger.getLogger(AdminEnqueteServlet.class);

	@Override
	protected int handleGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String idParam = request.getParameter("id");
		@SuppressWarnings("unchecked")
		List<String> errors = (List<String>) request.getAttribute("errors");
		if(idParam == null) {
			setEnqueteFormAttributes(request, response);

		} else {
			
			try {
				final int id = Integer.parseInt(idParam);
				DAOManager daoManager = null;
				try {
					daoManager  = (new DAOFactory()).createDAOManager(DAOFactory.PERSISTENCEMODE.MYSQL);
				} catch (DAOException daoe) {
					logger.fatal(daoe.toString());
					throw new ServletException(daoe.getMessage() + "\nPlease configure the resource in the META_INF/context.xml file");
				}
				Survey survey = (Survey) daoManager.transactionAndClose(new DAOCommand() {
					
					@Override
					public Object execute(DAOManager daoManager) throws DAOException {
						return daoManager.getSurveyDAO().findSurveyWithQuestionsAndCreator(id);
					}
				});
				if (survey == null) {
					logger.error("No survey found with id: " + id);
					errors.add("No survey found with id: " + id);
				}
				request.setAttribute("survey", survey);
			} catch (DAOException daoe) {
				logger.error(daoe.toString());
				errors.add(daoe.getMessage());
			} catch (NumberFormatException nfe) {
				logger.error(nfe.getMessage());
				errors.add("id moet een numerieke waarde hebben");
			}
			setEnqueteViewAttributes(request, response);
		}
		return 200;
	}

	@Override
	protected int handlePost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(false);
		User currentUser = (User)session.getAttribute("user");
		
		final Survey survey; //de referentie mag nooit veranderen
		
		Survey s = (Survey) session.getAttribute("survey");
		if (s == null) {
			survey = new Survey(); 
			request.setAttribute("survey", survey);
			survey.setCreator(currentUser);
		} else {
			survey = s;
		}
		BeanUtils.mapSurveyPostParameters(survey, request.getParameterMap(), logger);
		
		
		@SuppressWarnings("unchecked")
		List<String> errors = (List<String>) request.getAttribute("errors");
		
		if(!survey.isValidForForm(errors)) {
			setEnqueteFormAttributes(request, response);
		} else {
			//bewaar in sessie
			session.setAttribute("survey", survey);
			
			//check of "bewaar" gedrukt is
			String actie = request.getParameter("save");
			if(actie != null) {
				// bewaar gedrukt
				boolean saved = false;
				if(survey.isValid(errors)) {
					DAOManager daoManager = null;
					try {
						daoManager  = (new DAOFactory()).createDAOManager(DAOFactory.PERSISTENCEMODE.MYSQL);
					} catch (DAOException daoe) {
						logger.fatal(daoe.toString());
						throw new ServletException(daoe.getMessage() + "\nPlease configure the resource in the META_INF/context.xml file");
					}
					
					try {
						daoManager.transactionAndClose(new DAOCommand() {
							
							@Override
							public Object execute(DAOManager daoManager) throws DAOException {
								daoManager.getSurveyDAO().insertSurvey(survey);
								daoManager.getQuestionDAO().insertQuestionsOfSurvey(survey);
								return null;
							}
						});
						
						//remove survey from session -> survey is still in request for the forwarded page
						session.setAttribute("survey", null);
						request.setAttribute("success", "Survey is succesvol bewaard");
						saved = true;
					} catch (DAOException daoe) {
						logger.error(daoe.toString());
						errors.add(daoe.getMessage());
					}
				} 
				if (!saved) {
					setEnqueteFormAttributes(request, response);
				} else {
					setEnqueteViewAttributes(request, response);
				}
			} else {
				//check of "toevoegen" gedrukt is
				actie = request.getParameter("add");
				if (actie != null) {
					request.setAttribute("redirect", request.getContextPath() + "/admin/question");
					return 302;//redirect to questionpage
				}	
			}	
			
		}
		return 200;
	}
	
	private void setEnqueteFormAttributes(HttpServletRequest request, HttpServletResponse response) {
		setForm(request, true);
		setFormActionUrl(request, response.encodeURL(request.getContextPath() + "/admin/enquete"));
		setPage(request, "enqueteForm");
		setTitle(request, "Nieuwe enquete");
		setNavigationSelectedLink(request, 1);
		addHeaderLink(request, 1, "Bewaar", "save");
		addHeaderLink(request, 2, "Voeg vraag toe", "add");
	}
	
	private void setEnqueteViewAttributes(HttpServletRequest request, HttpServletResponse response) {
		setForm(request, false);
		setPage(request, "enqueteView");
		setTitle(request, "Bekijk enquete");
		setNavigationSelectedLink(request, 1);
	}

}
